--[[ 基础的服务器父类 ]]
local _M = class("BaseServer")
--======================================
--default params
local d = Ding
local Logger = d.Logger

local HTTPMETHOD = require("framework.constant").HTTPMETHOD
--======================================

function _M:ctor()
    self:lazyInit()
end

function _M:lazyInit()
    local method_, handler_
    for _, methodk in pairs(HTTPMETHOD) do
        local methodl = string.lower(methodk)
        self[string.format("_%s_handlers", methodl)] = {}
        self[string.format("_%s", methodl)] = function(self, uri)
            local handler = self[string.format("_%s_handlers", methodl)][uri]
            if (handler) then
                Logger:debug("Handle req:%s", methodl, uri)
                handler()
            else
                ngx.say(string.format("Not uri %s in router method<%s>!->", uri, methodl))
            end
        end
        self[methodl] = function(self, ...)
            local urimap = {...}
            for i = 1, #urimap , 2 do 
                uri = urimap[i]
                handler_ = urimap[i + 1]
                if not (type(uri) == "string" and  type(handler_) == "function") then 
                    Logger:error("regisetr uri_map failed!chk the params type!")
                    Logger:dump(handlers, "-->>>reg list")
                    break
                end
                Logger:debug("Svr %s register router %s handler...", methodl, uri)
                self[string.format("_%s_handlers", methodl)][uri] = handler_
            end
        end
    end
end

--直接连接db+cache
function _M:run()
    --@todo no use
    --in access
    -- self:_access_()

    --in content
    self:_content_()
end

--添加消息处理类
function _M:add_apihandle(routurl, handleobj)
    self._api_handlers[routurl] = handleobj
end

--ngx-access阶段的处理
function _M:_access_()
    --todo
    --暂时没有access阶段处理的内容
end

--ngx-conetent阶段的处理
function _M:_content_()
    local method = ngx.req.get_method()
    local uri = ngx.var.uri
    local isrouter, returi = self:_chk_routeruri(uri)
    Logger:info("Req:method<%s> && uri:<%s>, in router? %s", tostring(method), ngx.var.uri, isrouter)
    if isrouter then
        self[string.format("_%s", string.lower(method))](self, returi)
        return
    end
end

function _M:_chk_routeruri(fulluri)
    local is_, returi
    local luri = ngx.var.location
    local spos = string.find(fulluri, luri)
    if spos then
        is_ = true
        returi = fulluri == luri and "" or string.sub(fulluri, string.len(luri))
    end
    return is_, returi
end

return _M
